<template>
  <div class="questionnaire-form">
    <h1>修改问卷</h1>
    <div v-if="loading" class="loading">正在加载...</div>
    <div v-if="error" class="error">{{ error }}</div>
    <div v-if="success" class="success">问卷修改成功！</div>
    
    <form @submit.prevent="updateQuestionnaire" v-if="!loading && !initialLoading">
      <div class="form-group">
        <label for="title">问卷标题</label>
        <input 
          id="title"
          v-model="questionnaire.title" 
          placeholder="问卷标题" 
          required 
          class="form-control"
        />
      </div>
      
      <div class="form-group">
        <label for="description">问卷描述</label>
        <textarea 
          id="description"
          v-model="questionnaire.description" 
          placeholder="问卷描述"
          class="form-control"
        ></textarea>
      </div>
      
      <!-- 问题列表 -->
      <div 
        v-for="(question, qIndex) in questionnaire.questions" 
        :key="qIndex"
        class="question-item"
      >
        <div class="question-header">
          <h3>题目 {{ qIndex + 1 }}</h3>
          <button 
            @click.prevent="removeQuestion(qIndex)" 
            class="btn btn-danger btn-sm"
          >
            删除题目
          </button>
        </div>
        
        <div class="form-group">
          <label>问题内容</label>
          <input 
            v-model="question.content" 
            placeholder="问题内容" 
            required 
            class="form-control"
          />
        </div>
        
        <!-- 图片上传区域 -->
        <div class="form-group">
          <label>问题图片（可选）</label>
          <div class="upload-container">
            <input 
              type="file" 
              :id="`questionImage-${qIndex}`" 
              accept="image/*" 
              @change="handleImageUpload($event, qIndex)" 
              class="file-input" 
            />
            <button 
              type="button" 
              class="btn btn-secondary btn-sm" 
              @click="triggerFileInput(qIndex)"
            >
              选择图片
            </button>
          </div>
          <!-- 图片预览区域 -->
          <div class="image-preview" v-if="question.imageUrl">
            <img :src="getImageUrl(question.imageUrl)" alt="问题图片预览" />
            <button 
              type="button" 
              class="btn btn-danger btn-sm remove-image-btn" 
              @click="removeImage(qIndex)"
            >
              删除图片
            </button>
          </div>
        </div>
        
        <div class="form-group">
          <label>题目类型</label>
          <select v-model="question.type" class="form-control" @change="handleQuestionTypeChange(qIndex)">
            <option value="radio">单选题</option>
            <option value="checkbox">多选题</option>
            <option value="text">填空题</option>
          </select>
        </div>
        
        <!-- 选项区域（仅单选题和多选题显示） -->
        <div v-if="question.type === 'radio' || question.type === 'checkbox'" class="options-container">
          <label>选项列表</label>
          
          <div v-for="(option, oIndex) in question.options" :key="oIndex" class="option-item">
            <div class="option-input-group">
              <input 
                v-model="question.options[oIndex]" 
                placeholder="选项内容" 
                required 
                class="form-control"
              />
              <button 
                @click.prevent="removeOption(qIndex, oIndex)" 
                class="btn btn-danger btn-sm"
                :disabled="question.options.length <= 2"
              >
                删除
              </button>
            </div>
          </div>
          
          <button 
            @click.prevent="addOption(qIndex)" 
            class="btn btn-secondary btn-sm"
          >
            添加选项
          </button>
        </div>
      </div>
      
      <div class="button-group">
        <div class="add-question-group">
          <button 
            @click.prevent="addQuestion('radio')" 
            class="btn btn-secondary"
          >
            添加单选题
          </button>
          <button 
            @click.prevent="addQuestion('checkbox')" 
            class="btn btn-secondary"
          >
            添加多选题
          </button>
          <button 
            @click.prevent="addQuestion('text')" 
            class="btn btn-secondary"
          >
            添加填空题
          </button>
        </div>
        
        <button 
          type="submit" 
          class="btn btn-primary"
          :disabled="loading || questionnaire.questions.length === 0"
        >
          保存修改
        </button>
      </div>
    </form>
  </div>
</template>

<script>
import { defineComponent, reactive, ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';

export default defineComponent({
  setup() {
    const route = useRoute();
    const router = useRouter();
    const questionnaireId = route.params.id;
    
    const questionnaire = reactive({
      id: null,
      title: '',
      description: '',
      questions: []
    });
    
    const loading = ref(false);
    const initialLoading = ref(true);
    const error = ref('');
    const success = ref(false);
    
    // 加载问卷数据
    const loadQuestionnaire = async () => {
      initialLoading.value = true;
      error.value = '';
      
      try {
        const response = await fetch(`http://localhost:9001/api/questionnaires/${questionnaireId}`);
        if (!response.ok) {
          throw new Error('获取问卷失败');
        }
        
        const data = await response.json();
        
        // 将数据填充到表单中
        questionnaire.id = data.id;
        questionnaire.title = data.title;
        questionnaire.description = data.description;
        questionnaire.questions = data.questions || [];
        
      } catch (err) {
        console.error('获取问卷数据时出错:', err);
        error.value = '加载问卷失败: ' + err.message;
      } finally {
        initialLoading.value = false;
      }
    };
    
    // 处理图片URL，确保能正确显示
    const getImageUrl = (imageUrl) => {
      if (!imageUrl) return '';
      
      // 如果是绝对路径（以C:、/或\开头），则转换为相对URL
      if (imageUrl.startsWith('C:') || imageUrl.startsWith('/') || imageUrl.startsWith('\\')) {
        // 提取文件名
        const fileName = imageUrl.split(/[/\\]/).pop();
        const url = `http://localhost:9001/image/question/${fileName}`;
        return url;
      }
      
      // 如果已经是相对URL（以/image/开头），则加上服务器地址
      if (imageUrl.startsWith('/image/')) {
        const url = `http://localhost:9001${imageUrl}`;
        return url;
      }
      
      // 其他情况，直接返回原始URL
      return imageUrl;
    };
    
    // 添加新问题
    const addQuestion = (type) => {
      const newQuestion = {
        content: '',
        type: type,
        options: type === 'text' ? [] : ['选项1', '选项2'],
        imageUrl: null
      };
      
      questionnaire.questions.push(newQuestion);
    };
    
    // 删除问题
    const removeQuestion = (index) => {
      questionnaire.questions.splice(index, 1);
    };
    
    // 添加选项
    const addOption = (questionIndex) => {
      const optionCount = questionnaire.questions[questionIndex].options.length;
      questionnaire.questions[questionIndex].options.push(`选项${optionCount + 1}`);
    };
    
    // 删除选项
    const removeOption = (questionIndex, optionIndex) => {
      const options = questionnaire.questions[questionIndex].options;
      if (options.length > 2) {
        options.splice(optionIndex, 1);
      } else {
        error.value = '至少需要两个选项';
        setTimeout(() => {
          error.value = '';
        }, 3000);
      }
    };
    
    // 处理问题类型变更
    const handleQuestionTypeChange = (questionIndex) => {
      const question = questionnaire.questions[questionIndex];
      
      // 如果从填空题切换到选择题，添加默认选项
      if (question.type !== 'text' && question.options.length === 0) {
        question.options = ['选项1', '选项2'];
      }
      
      // 如果从选择题切换到填空题，清空选项
      if (question.type === 'text') {
        question.options = [];
      }
    };
    
    // 更新问卷
    const updateQuestionnaire = () => {
      if (questionnaire.questions.length === 0) {
        error.value = '请至少添加一个问题';
        return;
      }
      
      loading.value = true;
      error.value = '';
      success.value = false;
      
      fetch(`http://localhost:9001/api/questionnaires/${questionnaire.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(questionnaire)
      })
      .then(response => {
        if (!response.ok) {
          throw new Error('网络响应不正常');
        }
        return response.json();
      })
      .then(data => {
        console.log('问卷更新成功:', data);
        success.value = true;
        
        // 3秒后返回问卷列表页
        setTimeout(() => {
          router.push('/');
        }, 3000);
      })
      .catch(err => {
        console.error('更新问卷时出错:', err);
        error.value = '更新失败: ' + err.message;
      })
      .finally(() => {
        loading.value = false;
      });
    };
    
    // 触发文件选择
    const triggerFileInput = (questionIndex) => {
      document.getElementById(`questionImage-${questionIndex}`).click();
    };
    
    // 处理图片上传
    const handleImageUpload = (event, questionIndex) => {
      const file = event.target.files[0];
      if (!file) return;
      
      // 显示上传中状态
      loading.value = true;
      error.value = '';
      
      // 构造一个FormData对象
      const formData = new FormData();
      formData.append('file', file);

      // 发送POST请求到后端
      fetch('http://localhost:9001/api/questionnaires/upload-image', {
        method: 'POST',
        body: formData,
      })
      .then(response => {
        if (!response.ok) {
          throw new Error('图片上传失败');
        }
        return response.text();
      })
      .then(imageUrl => {
        // 保存返回的图片URL
        questionnaire.questions[questionIndex].imageUrl = imageUrl;
      })
      .catch(err => {
        console.error('图片上传出错:', err);
        error.value = '图片上传失败: ' + err.message;
        setTimeout(() => {
          error.value = '';
        }, 3000);
      })
      .finally(() => {
        loading.value = false;
      });
    };
    
    // 删除已上传的图片
    const removeImage = (questionIndex) => {
      questionnaire.questions[questionIndex].imageUrl = null;
    };
    
    // 组件挂载时加载问卷数据
    onMounted(loadQuestionnaire);
    
    return {
      questionnaire,
      loading,
      initialLoading,
      error,
      success,
      addQuestion,
      removeQuestion,
      addOption,
      removeOption,
      handleQuestionTypeChange,
      updateQuestionnaire,
      triggerFileInput,
      handleImageUpload,
      removeImage,
      getImageUrl
    };
  }
});
</script>

<style scoped>
.questionnaire-form {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-control {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-top: 5px;
}

.question-item {
  border: 1px solid #eee;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.question-header h3 {
  margin: 0;
}

.options-container {
  margin-top: 15px;
  padding: 10px;
  border: 1px dashed #ddd;
  border-radius: 4px;
  background-color: #fff;
}

.option-item {
  margin-bottom: 10px;
}

.option-input-group {
  display: flex;
  gap: 10px;
}

.option-input-group .form-control {
  flex: 1;
}

.button-group {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.add-question-group {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 0.9em;
}

.btn-primary {
  background-color: #4CAF50;
  color: white;
}

.btn-secondary {
  background-color: #2196F3;
  color: white;
}

.btn-danger {
  background-color: #f44336;
  color: white;
}

.btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.loading, .error, .success {
  padding: 10px;
  margin-bottom: 15px;
  border-radius: 4px;
}

.loading {
  background-color: #f9f9f9;
}

.error {
  background-color: #ffebee;
  color: #c62828;
}

.success {
  background-color: #e8f5e9;
  color: #2e7d32;
}

/* 图片上传相关样式 */
.upload-container {
  display: flex;
  align-items: center;
  margin-top: 5px;
}

.file-input {
  display: none;
}

.image-preview {
  margin-top: 10px;
  position: relative;
  display: inline-block;
}

.image-preview img {
  max-width: 100%;
  max-height: 200px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.remove-image-btn {
  position: absolute;
  top: 5px;
  right: 5px;
}
</style> 